import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import {useRef, useState} from 'react';
import {merchantList, merchantUpdate} from "@/services/bz/api";

type GithubIssueItem = {
  id: number;
  merchantCode: string;
  status: string;
  webUrl: string;
};

const columns: ProColumns<GithubIssueItem>[] = [
  {
    title: '商户号',
    dataIndex: 'merchantCode',
    width: 200,
    search:false,
    editable:false
  },
  {
    title: '运行状态',
    dataIndex: 'status',
    width: 200,
    valueType: 'select',
    search:false,
    valueEnum: {
      open: {
        text: '1',
        status: '1',
      },
      closed: {
        text: '2',
        status: '2',
      }
    },
  },
  {
    editable:false,
    title: '网址',
    key: 'webUrl',
    dataIndex: 'webUrl',
    hideInSearch: true,
  },
  {
    title: '操作',
    valueType: 'option',
    key: 'option',
    width: 200,
    render: (text, record, _, action) => [
      <a
        key="editable"
        onClick={() => {
          action?.startEditable?.(record.id);
        }}
      >
        编辑
      </a>
    ],
  },
];

export default () => {
  const actionRef = useRef<ActionType>();
  const [merchantData, setMerchantData] = useState([]);
  return (
    <ProTable<GithubIssueItem>
      columns={columns}
      actionRef={actionRef}
      cardBordered
      request={async () => {
        let response = await merchantList();
        setMerchantData(response.data.list)
        return {data: response.data == null ? [] : response.data.list};
      }}
      editable={{
        type: 'multiple',
        onSave(value){
          let code="";
          merchantData.map((item)=>{
            if (item.id == value){
              code=item.merchantCode
            }
          })
          console.log('value: ', code);
          merchantUpdate(code).then(()=>{
            actionRef.current?.reload()
          })
        }
      }}
      columnsState={{
        persistenceKey: 'pro-table-singe-demos',
        persistenceType: 'localStorage',
        onChange(value) {
          console.log('value: ', value);
        },
      }}
      rowKey="id"
      search={{
        labelWidth: 'auto',
      }}
      form={{
        // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
        syncToUrl: (values, type) => {
          console.log("~~~~")
          if (type === 'get') {
            return {
              ...values,
              created_at: [values.startTime, values.endTime],
            };
          }
          return values;
        },
      }}
      search={false}
      pagination={{
        pageSize: 20,
        onChange: (page) => console.log(page),
      }}
      dateFormatter="string"
      headerTitle={"商户列表"}
      options={false}
      revalidateOnFocus={false}
    />
  );
};
